package cn.ac.siom.query.action;


import cn.ac.siom.query.util.action.DefaultAction;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/home/*")
public class PDFdownload extends DefaultAction {

    @ResponseBody
    @RequestMapping(value = "PDFdown", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public void PDFdown(Integer i_id, HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException {
        String referer = request.getHeader("Referer");
        String Xip = request.getHeader("X-Real-IP");
        String XFor = request.getHeader("X-Forwarded-For");
        System.out.println("真实IP" + Xip);
        System.out.println("代理IP" + XFor);
        System.out.println("sd" + referer);
        int RecordNO = i_id;
        if (referer == null) {
            String Newreferer = "http://www.optics.org.cn/web/detail?channelid=114677&extrasql=%E8%AE%B0%E5%BD%95%E5%8F%B7%3D" + RecordNO;
            System.out.println(Newreferer);
            URL url = new URL("http://www.optics.org.cn/web/download.jsp?tablename1=thesis&recordno1=" + RecordNO);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Charset", "UTF-8");
            conn.setRequestProperty("Referer", Newreferer);
            conn.setConnectTimeout(5000);
            //String Xip = conn.getHeaderField("X-Forwarded-For");
            //String XFor =conn.getHeaderField("X-Forwarded-For");
            //System.out.println("真实IP"+Xip);
            //System.out.println("代理IP"+XFor);
            TestIP testIP = new TestIP();
            //if (testIP.isInRange(Xip,"192.168.0.1/254")) {

            conn.setDoOutput(true);
            //得到输入流
            InputStream inputStream = conn.getInputStream();
            //获取自己数组
            byte[] getData = readInputStream(inputStream);
            Map<String, List<String>> map = conn.getHeaderFields();
            List<String> server = map.get("Content-Disposition");
            if (server != null) {
                String[] Content = server.get(0).split("=");
                String filename0 = Content[Content.length - 1];
                String filename = URLDecoder.decode(filename0);
                String mimeType = "application/x-msdownload;charset=UTF-8";
                response.setContentType(mimeType);
                response.setHeader("Content-Disposition", "inline; filename=\"" + new String(filename.getBytes(), "iso-8859-1") + "\"");
            }
            String mimeType = "application/x-msdownload;charset=UTF-8";
            response.setContentType(mimeType);
            OutputStream fos = response.getOutputStream();
            fos.write(getData);

            if (fos != null) {
                fos.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }
        }
        // }


    }

    public static byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }

    @ResponseBody
    @RequestMapping(value = "getIptest01", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public String getIpAdrress(HttpServletRequest request) {
        //private static Logger logger = Logger.getLogger(RandomCodeUtils.class);

        /**
         * 获取请求主机IP地址,如果通过代理进来，则透过防火墙获取真实IP地址;
         *
         * @param request
         * @return
         * @throws IOException
         */

        // 获取请求主机IP地址,如果通过代理进来，则透过防火墙获取真实IP地址

        String ip = request.getHeader("X-Forwarded-For");

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");

            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");

            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_CLIENT_IP");

                if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                    ip = request.getHeader("HTTP_X_FORWARDED_FOR");

                }
                if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                    ip = request.getRemoteAddr();

                }
            } else if (ip.length() > 15) {
                String[] ips = ip.split(",");
                for (int index = 0; index < ips.length; index++) {
                    String strIp = (String) ips[index];
                    if (!("unknown".equalsIgnoreCase(strIp))) {
                        ip = strIp;
                        break;
                    }
                }
            }

        }
        return ip;
    }

    @ResponseBody
    @RequestMapping(value = "getIptest", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public static final String getIpAddr(final HttpServletRequest request)
            throws Exception {
        if (request == null) {
            throw (new Exception("getIpAddr method HttpServletRequest Object is null"));
        }
        String ipString = request.getHeader("x-forwarded-for");
        if (StringUtils.isBlank(ipString) || "unknown".equalsIgnoreCase(ipString)) {
            ipString = request.getHeader("Proxy-Client-IP");
        }
        if (StringUtils.isBlank(ipString) || "unknown".equalsIgnoreCase(ipString)) {
            ipString = request.getHeader("WL-Proxy-Client-IP");
        }
        if (StringUtils.isBlank(ipString) || "unknown".equalsIgnoreCase(ipString)) {
            ipString = request.getRemoteAddr();
        }

        // 多个路由时，取第一个非unknown的ip
        final String[] arr = ipString.split(",");
        for (final String str : arr) {
            if (!"unknown".equalsIgnoreCase(str)) {
                ipString = str;
                break;
            }
        }

        return ipString;
    }


    @Override
    public String getText() {
        return null;
    }
}

